import { AskRequest, AskResponse, ExecutionTrace } from '@/types';

class ApiClient {
  private baseUrl: string;

  constructor() {
    // 在客户端环境中，使用相对路径
    this.baseUrl = typeof window !== 'undefined' ? '' : 'http://localhost:3000';
  }

  // 发送问答请求
  async ask(request: AskRequest): Promise<AskResponse> {
    const response = await fetch(`${this.baseUrl}/api/ask`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(request),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  }

  // 获取执行追踪
  async getTrace(chatflowId: string, sessionId: string): Promise<ExecutionTrace> {
    const response = await fetch(
      `${this.baseUrl}/api/trace?chatflowId=${chatflowId}&sessionId=${sessionId}`,
      {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
      }
    );

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  }

  // 获取聊天历史
  async getChatHistory(chatflowId: string, sessionId?: string): Promise<any[]> {
    const url = sessionId 
      ? `${this.baseUrl}/api/chatmessage/${chatflowId}?sessionId=${sessionId}`
      : `${this.baseUrl}/api/chatmessage/${chatflowId}`;
    
    const response = await fetch(url, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return response.json();
  }
}

export const apiClient = new ApiClient();
